package com.whfc;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

/**
 * @Description 定时任务线程池配置
 * @Author hw
 * @Date 2020/9/12 17:37
 * @Version 1.0
 */
@Configuration
@ConditionalOnMissingBean(XxlJobConfig.class)
public class ScheduleConfig implements SchedulingConfigurer, AsyncConfigurer {

    private static final int corePoolSize = 5;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("task-schedule-%d").build();
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
        taskRegistrar.setScheduler(executorService);
    }

    @Override
    public Executor getAsyncExecutor() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("task-async-%d").build();
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
        return executorService;
    }
}
